/*
687.最长同值路径
https://leetcode.cn/problems/longest-univalue-path/description/
中等 2024/11/10
*/


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
        ans=0
        if root is None:
            return 0
        def dfs(node:Optional[TreeNode],val:int) -> int:
            nonlocal ans  # 声明 ans 是外部作用域的变量
            if node is None:
                return 0
            l=dfs(node.left,node.val)
            r=dfs(node.right,node.val)
            ans=max(l+r,ans)
            if val==node.val:
                return max(l,r)+1
            else :
                return 0
        dfs(root,root.val)
        return ans

            

        